import { ExpertAddTime } from '@/api/expert';
import { Button, DatetimePicker, Divider, Icon, Popup } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useSetState } from 'ahooks';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';

export default function useCustom(props: {
  date: string;
  onSuccess: Function;
}) {
  const [show, setShow] = useState<boolean>(false);
  const [mode, setMode] = useState<'start' | 'end'>('start');

  const [formValues, setFormValues] = useSetState<{
    start: string | undefined;
    end: string | undefined;
  }>({
    start: '12:00',
    end: '14:00',
  });

  const minHour = useMemo(
    () =>
      dayjs(`${dayjs().format('YYYY/MM/DD')} ${formValues.start}`)
        .add(2, 'hour')
        .hour(),
    [formValues.start]
  );

  const { runAsync, loading } = useRequest(ExpertAddTime, { manual: true });

  function renderNode() {
    return (
      <Popup
        zIndex={9999}
        show={show}
        round
        position='bottom'
        style={{
          overflow: 'initial',
          paddingBottom: 'calc(64px + env(safe-area-inset-bottom))',
        }}
      >
        <View className=' absolute right-2 -top-[90px]'>
          <Icon
            className='text-3xl text-white'
            name='close'
            onClick={() => setShow(false)}
          />
        </View>

        <View className='p-4 text-lg font-bold text-black'>
          自定义时段
          <Text className=' text-xs text-gary4'>（咨询时段至少2小时）</Text>
        </View>
        <Divider className='m-0' />
        <View className='p-4 space-y-3'>
          <View
            className={classNames(
              'flex justify-between p-4 border-4 border-gary5 border-solid rounded-lg px-4 text-xs text-gary4',
              {
                'border-primary bg-[#EFF3FA]': mode === 'start',
              }
            )}
            onClick={() => setMode('start')}
          >
            开始时间：
            <Text className=' font-bold text-primary'>{formValues.start}</Text>
          </View>
          {mode === 'start' && (
            <DatetimePicker
              onInput={(e) => {
                setFormValues({ start: e.detail as string });
                //更新结束时间得值

                setFormValues({
                  end: dayjs(`${dayjs().format('YYYY/MM/DD')} ${e.detail}`)
                    .add(2, 'hour')
                    .format('HH:mm'),
                });
              }}
              value={formValues.start}
              showToolbar={false}
              type='time'
            />
          )}

          <View
            className={classNames(
              'flex justify-between p-4 border-4 border-gary5 border-solid rounded-lg px-4 text-xs text-gary4',
              {
                'border-primary bg-[#EFF3FA]': mode === 'end',
              }
            )}
            onClick={() => {
              setMode('end');
              console.log('value is --', formValues.end);
            }}
          >
            结束时间：
            <Text className=' font-bold text-primary'>{formValues.end}</Text>
          </View>

          {mode === 'end' && (
            <DatetimePicker
              minHour={minHour}
              onInput={(e) => {
                setFormValues({ end: e.detail as string });
              }}
              value={formValues.end}
              showToolbar={false}
              type='time'
            />
          )}

          <Button
            block
            type='primary'
            loading={loading}
            onClick={async () => {
              if (!formValues.start || !formValues.end) return;

              //比较两个时间差
              const start = dayjs(`${props.date} ${formValues.start}`);
              const end = dayjs(`${props.date} ${formValues.end}`);
              const hoursDifference = end.diff(start, 'hour');

              if (hoursDifference < 2)
                return Taro.showToast({
                  title: '不能提交小于2小时的时段',
                  icon: 'none',
                });

              await runAsync({
                date: props.date,
                start_time: formValues.start,
                end_time: formValues.end,
              });

              props.onSuccess();
              setShow(false);
            }}
          >
            确定
          </Button>
        </View>
      </Popup>
    );
  }

  return {
    renderNode,
    open: () => setShow(true),
  };
}
